package handler

import (
	"MulticloudManagement/internal/model"
	"MulticloudManagement/pkg/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type Auth struct {
	DB     *gorm.DB
	Config *utils.Config
}

// LoginView 登录页面
func (a *Auth) LoginView(c *gin.Context) {
	c.HTML(200, "login.html", nil)
}

// RegisterView 注册页面
func (a *Auth) RegisterView(c *gin.Context) {
	c.HTML(200, "register.html", nil)
}

func (a *Auth) Register(c *gin.Context) {
	// 获取表单数据
	username := c.PostForm("username")
	password := c.PostForm("password")
	email := c.PostForm("email")
	phone := c.PostForm("phone")

	password, err := utils.BcryptEncode(password)
	if err != nil {
		c.String(200, "密码加密失败")
		return
	}

	// 将数据插入到数据库(模型类,迁移到数据库)
	user := model.User{
		Username: username,
		Password: password,
		Email:    email,
		Phone:    phone,
	}
	// 插入数据
	err = a.DB.Create(&user).Error
	if err != nil {
		c.JSON(500, gin.H{
			"message": "注册失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"username": username,
		"password": password,
		"email":    email,
		"phone":    phone,
	})
}

// Login 登录
func (a *Auth) Login(c *gin.Context) {
	// 获取表单数据
	username := c.PostForm("username")
	password := c.PostForm("password")
	// 验证表单数据
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"message": "用户名或密码不能为空",
		})
		return
	}
	// 验证用户名是否存在
	var user model.User
	a.DB.Where("username = ?", username).First(&user)
	if user.ID == 0 {
		c.String(200, "用户名不存在")
		return
	}

	// 验证密码是否正确
	if !utils.BcryptValidate(password, user.Password) {
		c.String(200, "密码错误")
		return
	}
	// 登录成功,生成token

	token, err := utils.GenerateJWT(user, a.Config.Jwt.Secret)
	if err != nil {
		c.String(500, "生成token失败")
		return
	}
	c.SetCookie("token", token, 3600, "/", "127.0.0.1", false, true)

	c.HTML(200, "dashboard.html", gin.H{
		"username": user.Username,
	})
}

func (a *Auth) CreateList(context *gin.Context) {
	context.String(200, "创建云主机")
}

func (a *Auth) DeleteList(context *gin.Context) {
	context.String(200, "删除云主机")
}

// Logout 登出
func (a *Auth) Logout(c *gin.Context) {
	c.SetCookie("token", "", -1, "/", "127.0.0.1", false, true)
	c.Redirect(302, "/login")
}

func NewAuth(db *gorm.DB, config *utils.Config) *Auth {
	return &Auth{
		DB:     db,
		Config: config,
	}
}
